import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import matplotlib.pyplot as plt

import copy

# 如果你有GPU，使用cuda
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# -------------------------------
# 1. 加载图像工具
# -------------------------------
imsize = 512 if torch.cuda.is_available() else 256  # 如果有GPU用大图

loader = transforms.Compose([
    transforms.Resize((imsize, imsize)),
    transforms.ToTensor()
])

def image_loader(image_name):
    image = Image.open(image_name)
    image = loader(image).unsqueeze(0)  # 增加batch维
    return image.to(device, torch.float)

# -------------------------------
# 2. 展示图像工具
# -------------------------------
unloader = transforms.ToPILImage()

def imshow(tensor, title=None):
    image = tensor.cpu().clone()
    image = image.squeeze(0)
    image = unloader(image)
    plt.imshow(image)
    if title:
        plt.title(title)
    plt.axis('off')
    plt.show()

# -------------------------------
# 3. 加载内容图像 & 风格图像
# -------------------------------
content_img = image_loader("content.jpg")
style_img = image_loader("style.jpg")

# assert content_img.size() == style_img.size(), \
#     "内容图像与风格图像必须尺寸一致"
def load_and_resize(image_path, target_size=None):
    image = Image.open(image_path).convert('RGB')  # 确保RGB格式
    
    if target_size:
        # 保持宽高比的resize
        w, h = image.size
        ratio = min(target_size[0]/w, target_size[1]/h)
        new_size = (int(w*ratio), int(h*ratio))
        image = image.resize(new_size, Image.LANCZOS)
    
    return loader(image).unsqueeze(0).to(device)

# 使用示例（自动调整到相同尺寸）
target_size = (512, 512) if torch.cuda.is_available() else (256, 256)
content_img = load_and_resize("1.jpg", target_size)
style_img = load_and_resize("style.jpg", target_size)
# -------------------------------
# 4. 搭建VGG19网络并提取特征
# -------------------------------
cnn = models.vgg19(pretrained=True).features.to(device).eval()

# 归一化层
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)

# -------------------------------
# 5. 定义内容损失 & 风格损失
# -------------------------------
class ContentLoss(nn.Module):
    def __init__(self, target):
        super(ContentLoss, self).__init__()
        # target需detach
        self.target = target.detach()

    def forward(self, input):
        self.loss = nn.functional.mse_loss(input, self.target)
        return input

def gram_matrix(input):
    b, c, h, w = input.size()
    features = input.view(b * c, h * w)
    G = torch.mm(features, features.t())
    return G.div(b * c * h * w)

class StyleLoss(nn.Module):
    def __init__(self, target_feature):
        super(StyleLoss, self).__init__()
        self.target = gram_matrix(target_feature).detach()

    def forward(self, input):
        G = gram_matrix(input)
        self.loss = nn.functional.mse_loss(G, self.target)
        return input

# -------------------------------
# 6. 添加归一化模块
# -------------------------------
class Normalization(nn.Module):
    def __init__(self, mean, std):
        super(Normalization, self).__init__()
        self.mean = mean.view(-1,1,1)
        self.std = std.view(-1,1,1)

    def forward(self, img):
        return (img - self.mean) / self.std

# -------------------------------
# 7. 搭建新的模型
# -------------------------------
content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']

def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
                               style_img, content_img,
                               content_layers=content_layers_default,
                               style_layers=style_layers_default):
    cnn = copy.deepcopy(cnn)

    normalization = Normalization(normalization_mean, normalization_std).to(device)
    content_losses = []
    style_losses = []

    model = nn.Sequential(normalization)

    i = 0  # 累计层数
    for layer in cnn.children():
        if isinstance(layer, nn.Conv2d):
            i += 1
            name = 'conv_{}'.format(i)
        elif isinstance(layer, nn.ReLU):
            name = 'relu_{}'.format(i)
            layer = nn.ReLU(inplace=False)
        elif isinstance(layer, nn.MaxPool2d):
            name = 'pool_{}'.format(i)
        elif isinstance(layer, nn.BatchNorm2d):
            name = 'bn_{}'.format(i)
        else:
            raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))

        model.add_module(name, layer)

        if name in content_layers:
            target = model(content_img).detach()
            content_loss = ContentLoss(target)
            model.add_module("content_loss_{}".format(i), content_loss)
            content_losses.append(content_loss)

        if name in style_layers:
            target_feature = model(style_img).detach()
            style_loss = StyleLoss(target_feature)
            model.add_module("style_loss_{}".format(i), style_loss)
            style_losses.append(style_loss)

    # 截断后面多余的层
    for i in range(len(model) -1, -1, -1):
        if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
            break
    model = model[:(i+1)]

    return model, style_losses, content_losses

# -------------------------------
# 8. 开始训练
# -------------------------------
input_img = content_img.clone()
input_img.requires_grad_(True)

model, style_losses, content_losses = get_style_model_and_losses(cnn,
    cnn_normalization_mean, cnn_normalization_std, style_img, content_img)

optimizer = optim.LBFGS([input_img])

num_steps = 300

print('开始优化...')
run = [0]
while run[0] <= num_steps:
    def closure():
        input_img.data.clamp_(0, 1)

        optimizer.zero_grad()
        model(input_img)
        style_score = 0
        content_score = 0

        for sl in style_losses:
            style_score += sl.loss
        for cl in content_losses:
            content_score += cl.loss

        loss = style_score * 1000000 + content_score
        loss.backward()

        if run[0] % 50 == 0:
            print("step {}: Style Loss : {:4f} Content Loss: {:4f}".format(
                  run[0], style_score.item(), content_score.item()))
            imshow(input_img, title='输出图像')

        run[0] += 1
        return style_score + content_score

    optimizer.step(closure)

# -------------------------------
# 9. 保存最终结果
# -------------------------------
input_img.data.clamp_(0, 1)
imshow(input_img, title='最终生成图像')
input_img = input_img.squeeze(0).cpu()
final_img = unloader(input_img)
final_img.save("output_style_transfer.png")
print("已保存输出到 output_style_transfer.png")
